import moment from 'moment';
import OSS from 'ali-oss'


const token = {
  // access_key_id: 'LTAIpojgNESiRSg1', // oss的key_id
  // access_key_secret: 'n5ntZDO9dpQaifEjESQyA0uTu92KUj', // oss的secret
  // OSS_ENDPOINT: 'oss-cn-shanghai', // 自己oss服务器的配置信息
  // OSS_BUCKET: 'xiaomayou', // 自己oss服务器的配置信息

  // 返回的是文件流，需要加一个域名才可是文件方式返回
  access_key_id: 'LTAI4Fdqx1ubZUKst9WnKU9w', // oss的key_id  
  access_key_secret: 'zkvcPZCVxFHdkYQAg3c2aX1nJONyvl', // oss的secret  
  OSS_ENDPOINT: 'oss-cn-shenzhen', // 自己oss服务器的配置信息
  OSS_BUCKET: 'gangmao', // 自己oss服务器的配置信息
  // LTAIpojgNESiRSg1
  // n5ntZDO9dpQaifEjESQyA0uTu92KUj
}

const client = () => {
  return OSS({
    accessKeyId: token.access_key_id,
    accessKeySecret: token.access_key_secret,
    region: token.OSS_ENDPOINT,
    bucket: token.OSS_BUCKET,
  });
}

const uploadPath = (path, file) => {
  // 上传文件的路径，使用日期命名文件目录
  return `${path}/${moment().format('YYYYMMDD')}/${file.name.split(".")[0]}-${file.uid}.${file.type.split("/")[1]}`
  // return `android.${file.type.split("/")[1]}`
}


//文件上传 https://help.aliyun.com/document_detail/111268.html?spm=a2c4g.11186623.6.1316.22d21a45FFtqjj
export const UploadToOss = (path, file) => {
  const url = uploadPath(path, file)
  return new Promise((resolve, reject) => {
    client().put(url, file).then(data => {
      // console.log('data' + JSON.stringify(data))
      let uri = '';
      if (data.res.requestUrls[0].indexOf('?upload') > -1) {
        uri = data.res.requestUrls[0].substring(0, data.res.requestUrls[0].indexOf('?upload'));
      } else {
        uri = data.res.requestUrls[0];
      }
      resolve(uri);
    }).catch(error => {
      reject(error)
    })
  })
}

export function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}


//分片上传
export const UploadToOssmultipartUpload = (path, file) => {
  const url = uploadPath(path, file)
  return new Promise((resolve, reject) => {
    client().multipartUpload(url, file).then(data => {
      // console.log('data' + JSON.stringify(data))
      let uri = '';
      if (data.res.requestUrls[0].indexOf('?upload') > -1) {
        uri = data.res.requestUrls[0].substring(0, data.res.requestUrls[0].indexOf('?upload'));
      } else {
        uri = data.res.requestUrls[0];
      }
      resolve(uri);
    }).catch(error => {
      reject(error)
    })
  })
}
